package com.guoheng.safe.manager.upload;

import com.guoheng.safe.manager.log.LogManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.UUID;

/**
 * 类功能描述:　UploadManager
 *
 * @author Eternal
 * @date 2019-38-15 14:38
 */
@Component
public class UploadManager {

    private static final Logger LOG = LoggerFactory.getLogger(LogManager.class);

    @Value("${spring.servlet.multipart.location}")
    private String picturePath;

    @Value("${server.port}")
    private String port ;

    @Value("${server.servlet.context-path}")
    private String path;

    @SuppressWarnings("all")
    public String uploadPicture(MultipartFile picture){

        //获取图片类型
        String exName = picture.getOriginalFilename().substring(picture.getOriginalFilename().lastIndexOf("."));
        //图片重命名
        String fileName = UUID.randomUUID().toString().replaceAll("-", "") + exName;

        File file = new File(picturePath + fileName);
        if(!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }

        try {
            picture.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }

        InetAddress localHost = null;
        try {
            localHost = Inet4Address.getLocalHost();
        } catch (UnknownHostException e) {
            LOG.error(e.getMessage(),e);
        }
        String ip = localHost.getHostAddress();
        return "http://" + ip + ":" + port + path + "/" +fileName;
    }
}
